package com.miaopasi.securitydemo.config.security.filter;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.miaopasi.securitydemo.config.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token解析过滤器
 *
 * @author lixin
 */
@Component("tokenFilter")
public class TokenFilter extends OncePerRequestFilter implements Filter {

    private final AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    public TokenFilter(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        Console.log("进入[token解析过滤器]");
        // 在请求头中获取token
        String token = ServletUtil.getHeader(request, "token", CharsetUtil.CHARSET_UTF_8);
        Console.log("请求token值，{}", token);
        // 解析token
        JwtTokenUtil.isExpiration(token);
        // 校验通过，就放行
        filterChain.doFilter(request, response);
    }
}
